<template>
  <div class="common-wrapper">
    <a-form-model ref="ruleForm" :rules="rules" :model="form" layout="inline">
      <a-row :gutter="16">
        <a-col class="gutter-row" :span="11">
          <a-form-model-item label="选择部门">
            <div style="display: flex; with: 100%">
              <a-button style="margin: 0 20px" type="primary" @click="selectAll">全部部门</a-button>
              <a-select
                style="width: 400px"
                mode="multiple"
                placeholder="请选择部门"
                v-model="form.department"
                @change="handleChange"
              >
                <a-select-option v-for="item in departmentList" :key="item.pkey">
                  {{ item.dep_name }}
                </a-select-option>
              </a-select>
            </div>
          </a-form-model-item>
          <a-form-model-item label="选择移除人员" prop="person_list">
            <a-transfer
              :data-source="staffList"
              :target-keys="targetKeys"
              :filter-option="(inputValue, item) => item.person_name.indexOf(inputValue) !== -1"
              :show-select-all="false"
              :showSearch="true"
              @change="onChange"
              :locale="locale"
              :titles="titles"
              :rowKey="(record) => record.person_idcard"
            >
              <template
                slot="children"
                slot-scope="{ props: { direction, filteredItems, selectedKeys }, on: { itemSelectAll, itemSelect } }"
              >
                <a-table
                  :row-selection="
                    getRowSelection({ direction, selectedKeys, itemSelectAll, itemSelect, filteredItems })
                  "
                  :columns="columns"
                  :dataSource="filteredItems"
                  :pagination="false"
                  size="small"
                  :scroll="{ y: 475 }"
                  :rowKey="(record) => record.person_idcard"
                />
              </template>
            </a-transfer>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="13">
          <a-form-model-item label="选择日期段" prop="date">
            <a-range-picker v-model="form.date" @change="onDateChange" style="width: 300px" />
          </a-form-model-item>
          <a-form-model-item label="考勤名称" prop="name">
            <a-input v-model="form.name" placeholder="请填写名称" style="width: 300px"></a-input>
          </a-form-model-item>
          <a-row :gutter="16" style="margin-top: 40px">
            <a-col :span="8">
              <a-card title="第一时段（上午）">
                <a-form-model-item label="开始时间" prop="seg1_begin_time">
                  <a-time-picker v-model="form.seg1_begin_time" />
                </a-form-model-item>
                <a-form-model-item label="上班时间" prop="seg1_on_time">
                  <a-time-picker v-model="form.seg1_on_time" />
                </a-form-model-item>
                <a-form-model-item label="下班时间" prop="seg1_off_time">
                  <a-time-picker v-model="form.seg1_off_time" />
                </a-form-model-item>
                <a-form-model-item label="结束时间" prop="seg1_end_time">
                  <a-time-picker v-model="form.seg1_end_time" />
                </a-form-model-item>
                <a-form-model-item label="是否启用">
                  <a-switch checked-children="启用" un-checked-children="禁用" v-model="form.seg1_enabled" />
                </a-form-model-item>
              </a-card>
            </a-col>
            <a-col :span="8">
              <a-card title="第二时段（下午）">
                <a-form-model-item label="开始时间" prop="seg2_begin_time">
                  <a-time-picker v-model="form.seg2_begin_time" />
                </a-form-model-item>
                <a-form-model-item label="上班时间" prop="seg2_on_time">
                  <a-time-picker v-model="form.seg2_on_time" />
                </a-form-model-item>
                <a-form-model-item label="下班时间" prop="seg2_off_time">
                  <a-time-picker v-model="form.seg2_off_time" />
                </a-form-model-item>
                <a-form-model-item label="结束时间" prop="seg2_end_time">
                  <a-time-picker v-model="form.seg2_end_time" />
                </a-form-model-item>
                <a-form-model-item label="是否启用">
                  <a-switch checked-children="启用" un-checked-children="禁用" v-model="form.seg2_enabled" />
                </a-form-model-item>
              </a-card>
            </a-col>
            <a-col :span="8">
              <a-card title="第三时段（晚班）">
                <a-form-model-item label="开始时间" prop="seg3_begin_time">
                  <a-time-picker v-model="form.seg3_begin_time" />
                </a-form-model-item>
                <a-form-model-item label="上班时间" prop="seg3_on_time">
                  <a-time-picker v-model="form.seg3_on_time" />
                </a-form-model-item>
                <a-form-model-item label="下班时间" prop="seg3_off_time">
                  <a-time-picker v-model="form.seg3_off_time" />
                </a-form-model-item>
                <a-form-model-item label="结束时间" prop="seg3_end_time">
                  <a-time-picker v-model="form.seg3_end_time" />
                </a-form-model-item>
                <a-form-model-item label="是否启用">
                  <a-switch checked-children="启用" un-checked-children="禁用" v-model="form.seg3_enabled" />
                </a-form-model-item>
              </a-card>
            </a-col>
          </a-row>
        </a-col>
      </a-row>
      <a-form-model-item style="margin-top: 20px">
        <a-button type="primary" @click="onSubmit" :loading="loading"> 保存 </a-button>
        <a-button style="margin-left: 10px" @click="resetForm"> 清空 </a-button>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>
<script>
import moment from 'moment'
import difference from 'lodash/difference'
import { getStaffList, getDepartmentList, batchsetplan, getClassSelect, getSpecialattendance, setSpecialattendance } from '@/api/plan'
export default {
  data () {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      visiblePlan: false,
      form: {
        date: [],
        id: 0,
        name: '',
        person_list: [],
        start_time: "",
        end_time: "",
        seg1_enabled: false,
        seg1_begin_time: "",
        seg1_end_time: "",
        seg1_on_time: "",
        seg1_off_time: "",
        seg2_enabled: false,
        seg2_begin_time: "",
        seg2_end_time: "",
        seg2_on_time: "",
        seg2_off_time: "",
        seg3_enabled: false,
        seg3_begin_time: "",
        seg3_end_time: "",
        seg3_on_time: "",
        seg3_off_time: ""
      },
      rules: {
        name: [{ required: true, message: '请填写考勤名称', trigger: 'blur' }],
        person_list: [{ required: true, validator: this.handleDepartment, trigger: 'blur' }],
        date: [{ required: true, message: '请选择日期段', trigger: 'change' }],
        seg1_begin_time: [{ required: true, message: '请选择时间段', trigger: 'change' }],
        seg1_end_time: [{ required: true, message: '请选择时间段', trigger: 'change' }],
        seg1_on_time: [{ required: true, message: '请选择时间段', trigger: 'change' }],
        seg1_off_time: [{ required: true, message: '请选择时间段', trigger: 'change' }],
        seg2_begin_time: [{ required: true, message: '请选择时间段', trigger: 'change' }],
        seg2_end_time: [{ required: true, message: '请选择时间段', trigger: 'change' }],
        seg2_on_time: [{ required: true, message: '请选择时间段', trigger: 'change' }],
        seg2_off_time: [{ required: true, message: '请选择时间段', trigger: 'change' }],
        seg3_begin_time: [{ required: true, message: '请选择时间段', trigger: 'change' }],
        seg3_end_time: [{ required: true, message: '请选择时间段', trigger: 'change' }],
        seg3_on_time: [{ required: true, message: '请选择时间段', trigger: 'change' }],
        seg3_off_time: [{ required: true, message: '请选择时间段', trigger: 'change' }]
      },
      departmentList: [],
      staffList: [],
      staffListParams: {
        page_index: 1,
        page_size: 10000,
        department_names: ''
      },
      targetKeys: [],
      columns: [
        {
          dataIndex: 'person_name',
          title: '员工姓名'
        },
        {
          dataIndex: 'person_idcard',
          title: '工号'
        }
      ],
      locale: {
        itemUnit: '人',
        searchPlaceholder: '请输入员工姓名'
      },
      titles: ['已选定人员', '移除人员'],
      subParams: {
        person_ids: [],
        plans: []
      },
      planList: [],
      selectedRows: [],
      selectedRowKeys: [],
      planColumns: [
        {
          dataIndex: 'plan_date',
          align: 'center',
          title: '日期'
        },
        {
          title: '星期',
          align: 'center',
          scopedSlots: { customRender: 'week' }
        },
        {
          title: '班制名称',
          align: 'center',
          scopedSlots: { customRender: 'class' }
        }
      ],
      class_key: '',
      loading: false

    }
  },
  filters: {
    weekFilter (value) {
      var dateArray = value.split("-");
      var date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
      return "日一二三四五六".charAt(date.getDay());
    }
  },
  computed: {
    hasSelected () {
      return this.selectedRowKeys.length > 0;
    }
  },
  mounted () {
    this.getDepartmentList()
    this.getPlanList()
    this.getSetting()
  },
  methods: {
    moment,
    // 获取特殊班制设置列表
    getSetting () {
      getSpecialattendance('get', {
        id: 5
      }).then(res => {
        console.log(res);
        if (res.statusCode === 200 && res.data) {
          this.staffList = res.data.person_list

          res.data.seg1_begin_time = moment(res.data.seg1_begin_time, 'HH:mm:ss')
          res.data.seg1_end_time = moment(res.data.seg1_end_time, 'HH:mm:ss')
          res.data.seg1_on_time = moment(res.data.seg1_on_time, 'HH:mm:ss')
          res.data.seg1_off_time = moment(res.data.seg1_off_time, 'HH:mm:ss')
          res.data.seg1_enabled = res.data.seg1_enabled === 1

          res.data.seg2_begin_time = moment(res.data.seg2_begin_time, 'HH:mm:ss')
          res.data.seg2_end_time = moment(res.data.seg2_end_time, 'HH:mm:ss')
          res.data.seg2_on_time = moment(res.data.seg2_on_time, 'HH:mm:ss')
          res.data.seg2_off_time = moment(res.data.seg2_off_time, 'HH:mm:ss')
          res.data.seg2_enabled = res.data.seg2_enabled === 1

          res.data.seg3_begin_time = moment(res.data.seg3_begin_time, 'HH:mm:ss')
          res.data.seg3_end_time = moment(res.data.seg3_end_time, 'HH:mm:ss')
          res.data.seg3_on_time = moment(res.data.seg3_on_time, 'HH:mm:ss')
          res.data.seg3_off_time = moment(res.data.seg3_off_time, 'HH:mm:ss')
          res.data.seg3_enabled = res.data.seg3_enabled === 1
          this.form = res.data
          this.form.date = [moment(res.data.start_time, 'YYYY-MM-DD'), moment(res.data.end_time, 'YYYY-MM-DD')]
        }
      })
    },
    handleDepartment (rule, value, callback) {
      if (this.form.person_list.length === 0) {
        return callback(new Error('请选择员工'))
      } else {
        return callback()
      }
    },
    // 选择全部部门
    async selectAll () {
      this.staffListParams.department_names = ''
      const { data } = await getStaffList(this.staffListParams)
      this.staffList = data.items
    },
    // 获取部门列表
    async getDepartmentList () {
      const { data } = await getDepartmentList()
      this.departmentList = data
    },
    // 选择部门
    async handleChange (value) {
      this.staffListParams.department_names = `${value}`
      if (!this.staffListParams.department_names) {
        this.staffList = []
        return
      }
      const { data } = await getStaffList(this.staffListParams)
      this.staffList = data.items
      this.form.person_list = []
      this.form.person_list = JSON.parse(JSON.stringify(data.items)).map(item => {
        return {
          pkey: item.pkey,
          person_idcard: item.person_idcard,
          person_name: item.person_name
        }
      })
    },
    // 选择日期段
    onDateChange (date, dateString) {
      console.log(date, dateString);
      this.form.date = date
      this.form.start_time = dateString[0]
      this.form.end_time = dateString[1]
      this.$refs.ruleForm.validateField("date")
      this.$forceUpdate()
    },
    onChange (nextTargetKeys) {
      this.targetKeys = nextTargetKeys
    },
    getRowSelection ({ direction, selectedKeys, itemSelectAll, itemSelect, filteredItems }) {
      if (direction === 'left') {
        const selectArr = []
        filteredItems.forEach(item => {
          selectArr.push({
            pkey: item.pkey,
            person_idcard: item.person_idcard,
            person_name: item.person_name
          })
        });
        this.form.person_list = selectArr
      }
      return {
        getCheckboxProps: item => ({ props: {} }),
        onSelectAll (selected, selectedRows) {
          const treeSelectedKeys = selectedRows.map(({ key }) => key)
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys)
          itemSelectAll(diffKeys, selected)
        },
        onSelect ({ key }, selected) {
          itemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys
      }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    // 获取班次下拉框
    async getPlanList () {
      const { data } = await getClassSelect()
      this.planList = data
    },
    openModel () {
      this.visiblePlan = true
    },
    handleCancelPlan () {
      this.class_key = ''
      this.selectedRowKeys = [];
      this.selectedRows = [];
      this.visiblePlan = false
    },
    onSubmit () {
      console.log(this.form)
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const postData = Object.assign({}, this.form);
          postData.seg1_enabled = postData.seg1_enabled ? 1 : 0
          postData.seg1_begin_time = postData.seg1_begin_time ? moment(postData.seg1_begin_time).format('HH:mm:ss') : '00:00:00'
          postData.seg1_end_time = postData.seg1_end_time ? moment(postData.seg1_end_time).format('HH:mm:ss') : '00:00:00'
          postData.seg1_on_time = postData.seg1_on_time ? moment(postData.seg1_on_time).format('HH:mm:ss') : '00:00:00'
          postData.seg1_off_time = postData.seg1_off_time ? moment(postData.seg1_off_time).format('HH:mm:ss') : '00:00:00'

          postData.seg2_enabled = postData.seg2_enabled ? 1 : 0
          postData.seg2_begin_time = postData.seg2_begin_time ? moment(postData.seg2_begin_time).format('HH:mm:ss') : '00:00:00'
          postData.seg2_end_time = postData.seg2_end_time ? moment(postData.seg2_end_time).format('HH:mm:ss') : '00:00:00'
          postData.seg2_on_time = postData.seg2_on_time ? moment(postData.seg2_on_time).format('HH:mm:ss') : '00:00:00'
          postData.seg2_off_time = postData.seg2_off_time ? moment(postData.seg2_off_time).format('HH:mm:ss') : '00:00:00'

          postData.seg3_enabled = postData.seg3_enabled ? 1 : 0
          postData.seg3_begin_time = postData.seg3_begin_time ? moment(postData.seg3_begin_time).format('HH:mm:ss') : '00:00:00'
          postData.seg3_end_time = postData.seg3_end_time ? moment(postData.seg3_end_time).format('HH:mm:ss') : '00:00:00'
          postData.seg3_on_time = postData.seg3_on_time ? moment(postData.seg3_on_time).format('HH:mm:ss') : '00:00:00'
          postData.seg3_off_time = postData.seg3_off_time ? moment(postData.seg3_off_time).format('HH:mm:ss') : '00:00:00'

          this.loading = true
          const { succeeded } = await setSpecialattendance('batchsetattendance', postData)
          if (succeeded) {
            this.$message.success('操作成功！')
            this.loading = false
          } else {
            this.$message.error('操作失败！')
            this.loading = false
          }
        } else {
          return false;
        }
      });
    },
    resetForm () {
      this.staffList = []
      const id = this.form.id
      this.form = {
        id,
        date: [],
        name: '',
        person_list: [],
        start_time: "",
        end_time: "",
        seg1_enabled: false,
        seg1_begin_time: "",
        seg1_end_time: "",
        seg1_on_time: "",
        seg1_off_time: "",
        seg2_enabled: false,
        seg2_begin_time: "",
        seg2_end_time: "",
        seg2_on_time: "",
        seg2_off_time: "",
        seg3_enabled: false,
        seg3_begin_time: "",
        seg3_end_time: "",
        seg3_on_time: "",
        seg3_off_time: ""
      }
      this.$refs.ruleForm.resetFields();
    }
  }
}
</script>
<style scoped lang='less'>
.common-wrapper {
  height: 100%;
  padding: 20px;
}
</style>
